package com.console.front.support;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DownloadImage {

	public synchronized static String dowmLoad(String url) {
		String name = new SimpleDateFormat("yyyyMMddHHmmssSSS")
				.format(new Date());
		String path = "/thumb/";
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdir();
		path += name + ".jpg";
		System.out.println("开始下载:"+url+"到:"+path);
		return download(url, path);
	}

	public static String download(String strUrl, String path) {
		URL url = null;
		try {
			url = new URL(strUrl);
		} catch (MalformedURLException e2) {
			e2.printStackTrace();
			return "";
		}

		InputStream is = null;
		try {
			is = url.openStream();
		} catch (IOException e1) {
			e1.printStackTrace();
			return "";
		}

		OutputStream os = null;
		try {
			os = new FileOutputStream(path);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			File file = new File(path);
			System.out.println("完成:"+file.getAbsolutePath());
			os.close();
			is.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
		return path;
	}
}